#!/bin/bash
# user-data logging: https://alestic.com/2010/12/ec2-user-data-output/ 
exec > >(tee /var/log/user-data.log|logger -t user-data -s 2>/dev/console) 2>&1

# http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html
# Liux instances startup script
# ===========================================
 # Install node
 echo [$(date '+%H:%M:%S')]: Installing nodejs > /var/log/user-data.log
 curl --silent --location https://rpm.nodesource.com/setup | bash -
 yum -y install nodejs npm

# Install UDPEmulator
 echo [$(date '+%H:%M:%S')]: Installing udpmulticastemulator > /var/log/user-data.log
 npm install udpmulticastemulator

# Install mono
#
# -> OPTIONAL ?
# apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF
# echo "deb http://download.mono-project.com/repo/debian wheezy main" | tee /etc/apt/sources.list.d/mono-xamarin.list
# yum update
# OPTIONAL ? <-
#
# rem http://stackoverflow.com/questions/24814275/unhandled-exception-in-mono-while-running-nancyfx
 echo [$(date '+%H:%M:%S')]: Installing mono > /var/log/user-data.log
 yum -y --fix-missing install mono-complete
# rem Running exe without "mono"
# http://askubuntu.com/questions/20246/running-a-mono-program-without-typing-in-mono-foo-exe
# https://www.kernel.org/doc/Documentation/mono.txt
 echo [$(date '+%H:%M:%S')]: Setting up mono executables > /var/log/user-data.log
 echo 'binfmt_misc /proc/sys/fs/binfmt_misc binfmt_misc none' > /etc/fstab
 mount -t binfmt_misc none /proc/sys/fs/binfmt_misc
 echo ':CLR:M::MZ::/usr/bin/mono:' > /proc/sys/fs/binfmt_misc/register

# Run emulator
 echo [$(date '+%H:%M:%S')]: Running udpmulticastemulator > /var/log/user-data.log
 nodejs /node_modules/udpmulticastemulator/UDPMulticastEmulator.index.js http://192.168.1.2:1234 &

# Deploy LucyGridNode
 echo [$(date '+%H:%M:%S')]: Installing lucygrid > /var/log/user-data.log
 mkdir lucygridnode
 cd lucygridnode
 wget --user=lucygrid@blueyellowmacaw.com --password=lucygrid ftp://blueyellowmacaw.com/lucygridnode/*
 chmod +x LucyGridNode.exe
 
 echo [$(date '+%H:%M:%S')]: Running lucygrid > /var/log/user-data.log
 /lucygridnode/LucyGridNode.exe &
